// @ts-nocheck
/**
 * @Date: 2022-04-07 19:26:40
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-07-15 20:45:18
 * @FilePath: \weibo-api\controller\userCtl.js
 * @Description: 用户数据处理
 */

const { User, UserRelations } = require("../model/index");
const { genPassword } = require("../utils/cryp");
const { SuccessModel, ErrorModel } = require("../ResModel");
const { DelBlogWithImg } = require("../tools");
//获取用户信息
const getUserInfo = async (userName, password) => {
  const whereOpt = {
    userName,
  };
  if (password) {
    password = genPassword(password);
    Object.assign(whereOpt, {
      password,
    });
  }
  const result = await User.findOne({
    //查询列
    attributes: [
      "id",
      "userName",
      "nickName",
      "avatar",
      "city",
      "description",
      "createdAt",
      "birthday",
      "gender",
    ],
    //查询条件
    where: whereOpt,
  });
  // console.log(result);
  if (result == null) {
    return result;
  }
  return result.dataValues;
};
//创建用户
const createUser = async (ctx, next) => {
  let { userName, password, gender, nickName } = ctx.request.body;
  password = genPassword(password);
  // console.log(userName, password, gender, nickName);
  try {
    const newUser = await User.create({
      userName,
      password,
      gender,
      nickName,
    });
    ctx.body = new SuccessModel({});
  } catch (error) {
    console.error(error);
    ctx.throw(500, "创建失败！，请稍后重试", error);
  }
};
//用户登陆
const login = async (ctx, next) => {
  const body = ctx.request.body;
  const res = await getUserInfo(body.userName, body.password);
  if (res) {
    ctx.session.userInfo = res;
    ctx.body = new SuccessModel(res);
  } else {
    ctx.body = new ErrorModel(404, "登陆失败");
  }
};
//更新用户信息
const updateUserInfo = async (ctx, next) => {
  //更新删除原来头像
  if (ctx.session.userInfo.avatar !== ctx.request.body.avatar) {
    DelBlogWithImg([ctx.session.userInfo.avatar]);
  }
  const body = ctx.request.body;
  const newData = {};
  for (const key in body) {
    if (!newData[key] && body[key] !== "") {
      if (key == "password") {
        newData[key] = genPassword(body[key]);
        break;
      } else {
        newData[key] = body[key];
      }
    }
  }
  const whereData = {
    userName: ctx.session.userInfo.userName,
    id: ctx.params.id,
  };

  const result = await User.update(newData, {
    where: whereData,
  });
  if (result[0] > 0) {
    Object.assign(ctx.session.userInfo, newData);
    ctx.body = new SuccessModel();
  } else {
    ctx.body = new ErrorModel(304, "修改失败");
  }
};
//退出登陆
const logout = async (ctx, next) => {
  delete ctx.session.userInfo;
  ctx.body = new SuccessModel();
};
//获取任意用户信息
const getOtherUserInfo = async (ctx, next) => {
  const id = ctx.params.id;
  const whereOpt = {
    id,
  };
  const result = await User.findOne({
    //查询列
    attributes: [
      "id",
      "userName",
      "nickName",
      "avatar",
      "city",
      "description",
      "createdAt",
      "birthday",
    ],
    //查询条件
    where: whereOpt,
  });
  if (result == null) {
    return result;
  }
  // console.log(result.dataValues);
  ctx.body = new SuccessModel(result.dataValues);
};
//获取粉丝列表
const getFansList = async (ctx, next) => {
  const { id } = ctx.params;
  let res = await User.findAndCountAll({
    attributes: [
      "id",
      "userName",
      "nickName",
      "avatar",
      "description",
      "gender",
    ],
    order: [["id", "desc"]],
    include: {
      model: UserRelations,
      where: {
        followerId: id,
      },
    },
  });
  let userList = res.rows.map((row) => row.dataValues);
  ctx.body = new SuccessModel({
    count: res.count,
    userList,
  });
};
// 获取关注列表
const getFollowList = async (ctx, async) => {
  const { id } = ctx.params;
  let res = await UserRelations.findAndCountAll({
    order: [["id", "desc"]],
    attributes: ["id"],
    include: [
      {
        model: User,
        attributes: [
          "id",
          "userName",
          "nickName",
          "avatar",
          "gender",
          "description",
        ],
      },
    ],
    where: {
      userId: id,
    },
  });

  let userList = res.rows.map((row) => row.dataValues);
  userList = userList.map((item) => {
    const user = item.user.dataValues;
    item.user = user;
    return item;
  });
  // console.log("查询结果是", userList, "id是", id);
  ctx.body = new SuccessModel({
    count: res.count,
    userList,
  });
};
//关注某人
const following = async (ctx, next) => {
  const { id: userId } = ctx.session.userInfo;
  const { id: followerId } = ctx.params;
  try {
    const res = await UserRelations.create({
      userId,
      followerId,
    });
    // console.log(res);
    ctx.body = new SuccessModel();
  } catch (error) {
    console.error(error);
    ctx.body = new ErrorModel(500, `关注失败！`);
  }
};
//取消关注
const unfollowing = async (ctx, next) => {
  const { id: userId } = ctx.session.userInfo;
  const { id: followerId } = ctx.params;

  const res = await UserRelations.destroy({
    where: { userId, followerId },
  });
  // console.log(res);
  if (res > 0) {
    ctx.body = new SuccessModel();
  } else {
    ctx.body = new ErrorModel(500, `取消关注失败！`);
  }
};
module.exports = {
  getUserInfo,
  createUser,
  login,
  updateUserInfo,
  logout,
  getOtherUserInfo,
  getFansList,
  following,
  unfollowing,
  getFollowList,
};
